import time
from threading import Lock

from django.shortcuts import render

# Create your views here.


from django.http import HttpResponse, StreamingHttpResponse, JsonResponse
from django.views.decorators.http import require_GET
from django.conf import settings
from .utils.stream_processor import camera_processors, generate_frames,latest_detections

@require_GET
def index(request):
    return HttpResponse(INDEX_HTML)

@require_GET
def video_feed(request, area_id):
    return StreamingHttpResponse(
        generate_frames(area_id),
        content_type='multipart/x-mixed-replace; boundary=frame'
    )

@require_GET
def get_latest_detections(request):
    with Lock():
        return JsonResponse({
            aid: [d for d in dets if time.time() - d['timestamp'] < settings.CONFIG['data_retention']]
            for aid, dets in latest_detections.items()
        })

@require_GET
def camera_status(request, area_id):
    processor = camera_processors.get(area_id)
    if processor:
        return JsonResponse({
            "status": processor.status,
            "last_update": time.time() - processor.last_valid_time
        })
    return JsonResponse({"status": "not_found"})

@require_GET
def get_camera_ids(request):
    return JsonResponse(list(settings.CAMERAS.keys()), safe=False)

INDEX_HTML = '''
    <!doctype html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>智能监控系统</title>
        <style>
          body { margin:0; background:#1a1a1a; color:white; }
          .video-grid { 
            display: grid; 
            grid-template-columns: repeat(auto-fit, minmax(640px, 1fr));
            gap: 20px; 
            padding: 20px;
          }
          .camera-card {
            position:relative;
            background:#000;
            border-radius:8px;
            overflow:hidden;
          }
          .status-badge {
            position:absolute;
            top:10px;
            left:10px;
            background:rgba(0,0,0,0.7);
            padding:8px 16px;
            border-radius:20px;
            display:flex;
            align-items:center;
          }
          .status-led {
            width:10px;
            height:10px;
            border-radius:50%;
            margin-right:8px;
          }
          .alert-banner {
            position:absolute;
            bottom:10px;
            left:10px;
            right:10px;
            background:rgba(255,0,0,0.5);
            padding:12px;
            border-radius:8px;
            animation:pulse 1.5s infinite;
          }
          @keyframes pulse {
            0% { opacity:0.6; }
            50% { opacity:0.3; }
            100% { opacity:0.6; }
          }
        </style>
      </head>
      <body>
        <div class="video-grid" id="videoContainer"></div>
        <script>
          // 自动刷新页面（3分钟）
          setInterval(() => location.reload(), 180000);

          function init() {
            fetch('/get_camera_ids')
              .then(res => res.json())
              .then(ids => {
                const container = document.getElementById('videoContainer');
                container.innerHTML = ids.map(id => `
                  <div class="camera-card">
                    <img src="/video_feed/${id}" style="width:100%;height:480px;object-fit:cover;">
                    <div class="status-badge" id="status-${id}">
                      <div class="status-led"></div>
                      ${id}
                    </div>
                    <div class="alert-banner" id="alert-${id}" style="display:none">
                      检测到异常行为！
                    </div>
                  </div>
                `).join('');

                setInterval(updateStatus, 5000);
                setInterval(updateAlerts, 1000);
              });
          }

          function updateStatus() {
            fetch('/get_camera_ids').then(res => res.json()).then(ids => {
              ids.forEach(id => {
                fetch(`/camera_status/${id}`)
                  .then(res => res.json())
                  .then(data => {
                    const badge = document.getElementById(`status-${id}`);
                    badge.style.color = data.status === 'connected' ? '#00ff00' : '#ff0000';
                    badge.querySelector('.status-led').style.background = 
                      data.status === 'connected' ? '#00ff00' : '#ff0000';
                  });
              });
            });
          }

          function updateAlerts() {
            fetch('/latest_detections').then(res => res.json()).then(data => {
              Object.keys(data).forEach(id => {
                const alert = document.getElementById(`alert-${id}`);
                alert.style.display = data[id].length > 0 ? 'block' : 'none';
              });
            });
          }

          init();
        </script>
      </body>
    </html>
    '''